
package com.fire.core.base.service;

import com.fire.core.base.model.Domain;
import com.fire.core.util.KnowledgeSessionHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.impl.KnowledgeBaseFactory;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.StatelessKieSession;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;

import java.io.UnsupportedEncodingException;


/**
 * @ClassName: BaseRuleEngine
 * @Description: TODO
 * @Author raoyuxing
 * @Date 2018/11/20 17:21 
 */
public class BaseRuleEngine {

    static KieContainer kieContainer;
    StatelessKieSession sessionStateless = null;
    KieSession  sessionStatefull = null;

    @BeforeClass
    public static void beforeClass(){
        kieContainer= KnowledgeSessionHelper.createRuleBase();
    }

    @Before
    public void setUp() throws Exception{
        System.out.println("------------Before------------");
    }
    @After
    public void tearDown() throws Exception{
        System.out.println("------------After------------");
    }

    protected void execute(String ksession, Domain domain){
        //用于设置drl文件的日期格式（drl的默认日期格式为 dd-MMM-yyyy，现改为 yyyy-MM-dd）
        System.setProperty("drools.dateformat", "yyyy-MM-dd");

        kieContainer= KnowledgeSessionHelper.createRuleBase();

        sessionStatefull = KnowledgeSessionHelper
                .getStatefulKnowledgeSession(kieContainer,ksession);
        sessionStatefull.insert(domain);
        sessionStatefull.fireAllRules();
    }

    protected void autoDeploy(String ksession,Domain domain){
        KieSession kSession = null;
        try {
            //用于设置drl文件的日期格式（drl的默认日期格式为 dd-MMM-yyyy，现改为 yyyy-MM-dd）
            System.setProperty("drools.dateformat", "yyyy-MM-dd");

            KnowledgeBuilder kb = KnowledgeBuilderFactory.newKnowledgeBuilder();
            //装入规则，可以装入多个
            kb.add(ResourceFactory.newByteArrayResource(ksession.getBytes("utf-8")), ResourceType.DRL);

            KnowledgeBuilderErrors errors = kb.getErrors();
            for (KnowledgeBuilderError error : errors) {
                System.out.println(error);
            }
            InternalKnowledgeBase kBase = KnowledgeBaseFactory.newKnowledgeBase();
            kBase.addPackages(kb.getKnowledgePackages());

            kSession = kBase.newKieSession();

            kSession.insert(domain);
            kSession.fireAllRules();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            if (kSession != null) {
                kSession.dispose();
            }
        }
    }
}
